package com.sunducation.co.mcw;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @description: 演示SimpleDateFormat线程不安全的场景
 * @author:chenwenbiao
 * @createTime:2019/7/9 15:28
 * @version：1.0
 **/
public class SimpleDateFormatTest{
    private SimpleDateFormat dateFormat ;
    public static void main(String[] args) {
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd");
        String todayString = "2019-07-09";
        String tomorrowString = "2019-07-10";
        try {
            Date today = dateFormat.parse(todayString);
            Date tomorrow = dateFormat.parse(tomorrowString);

            //打印出当时串的时间，方便对比
            System.out.println("today=" + today);
            System.out.println("tomorrow=" + tomorrow);

            //开启格式化线程，格式化日期
            Thread thread1 = new Thread(new Thread1(dateFormat,today));
            thread1.start();
            Thread thread2 = new Thread(new Thread2(dateFormat,tomorrow));
            thread2.start();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    
}
class Thread1 implements Runnable{
    private SimpleDateFormat dateFormat;
    private Date date;
    public Thread1(SimpleDateFormat dateFormat,Date date){
        this.dateFormat = dateFormat;
        this.date = date;
    }

    @Override
    public void run() {
        while (true){
            String strDate = dateFormat.format(date);
            System.out.println("today=" + strDate);

            // 如果不等于2019-07-09，证明出现线程安全问题了！！！！
            if(!"2019-07-09".equals(strDate)){
                System.exit(1);
            }
        }
    }
}
class Thread2 implements Runnable{
    private SimpleDateFormat dateFormat;
    private Date date;
    public Thread2(SimpleDateFormat dateFormat,Date date){
        this.dateFormat = dateFormat;
        this.date = date;
    }

    @Override
    public void run() {
        while (true){
            String strDate = dateFormat.format(date);
            System.out.println("tomorrow=" + strDate);

            // 如果不等于2019-07-10，证明出现线程安全问题了！！！！
            if(!"2019-07-10".equals(strDate)){
                System.exit(1);
            }
        }
    }
}